import { useEffect } from "react";
import { useDictionaryStore } from "@/store/useDictionaryStore";
import dictService from "@/api/services/system/dictService";

const useDictionary = (code: string) => {
  const { dictionaries, setDictionary, loading } = useDictionaryStore();

  useEffect(() => {
    // 如果字典数据不存在并且没有在加载，则进行加载
    if (!dictionaries[code] && !loading) {
      const getDictionaryItems = async () => {
        try {
          const data = await dictService.getItemByCode(code);
          // 格式化字典数据
          const formattedData = data.map((item: { itemText: string; itemValue: string; color: string }) => ({
            label: item.itemText,
            value: item.itemValue,
            color: item.color,
          }));
          setDictionary(code, formattedData);
        } catch (err) {
          console.error("获取字典数据失败:", err);
        }
      };

      getDictionaryItems();
    }
  }, [code, dictionaries, loading, setDictionary]);

  // 如果字典正在加载，返回一个空数组或其他占位符
  if (loading) return [];

  return dictionaries[code] || []; // 返回字典数据
};

export default useDictionary;
